package com.mdp.workflow.ru.listener.global;

import com.mdp.workflow.ru.listener.PushImMsgService;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.flowable.common.engine.api.delegate.event.FlowableEvent;
import org.flowable.common.engine.api.delegate.event.FlowableEventListener;
import org.flowable.common.engine.impl.event.FlowableEntityEventImpl;
import org.flowable.common.engine.impl.interceptor.CommandContext;
import org.flowable.engine.TaskService;
import org.flowable.engine.delegate.DelegateExecution;
import org.flowable.engine.impl.util.CommandContextUtil;
import org.flowable.task.service.impl.persistence.entity.TaskEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 任务节点前置监听处理类
 * 不生效，不知道为什么
 * @author: Lu Yang
 * @create: 2019-05-04 20:51
 **/
@Component
public class TaskAssignedListener implements FlowableEventListener {

	Log log=LogFactory.getLog(TaskAssignedListener.class);
	
	@Autowired
	private PushImMsgService pushMsgService;

	
	
	 public DelegateExecution getExecution(String executionId) {
	        if (executionId != null) {
	            CommandContext commandContext = CommandContextUtil.getCommandContext();
	            if (commandContext != null) {
	                return CommandContextUtil.getExecutionEntityManager(commandContext).findById(executionId);
	            }
	        }
	        return null;
	    }
	

    @Override
    public void onEvent(FlowableEvent event) {
		// TODO Auto-generated method stub
		 // 当前节点任务实体
    	TaskService taskService=CommandContextUtil.getProcessEngineConfiguration().getTaskService();
		FlowableEntityEventImpl eventImpl=(FlowableEntityEventImpl)event;
       TaskEntity taskEntity = (TaskEntity) (eventImpl).getEntity(); 
       DelegateExecution execution=this.getExecution(eventImpl.getExecutionId()); 
		
       String assignee=taskEntity.getAssignee();
       String mainTitle=(String) taskEntity.getVariable("mainTitle");
       String commentMsg=(String) taskEntity.getVariable("commentMsg");
       String taskName=taskEntity.getName();
       String bizUrl=(String) taskEntity.getVariable("bizUrl");
       pushMsgService.pushTaskMsgToIm(assignee, mainTitle, taskName, commentMsg,bizUrl);

		
	}

    @Override
    public boolean isFailOnException() {
        return false;
    }

    @Override
    public boolean isFireOnTransactionLifecycleEvent() {
        return false;
    }

    @Override
    public String getOnTransaction() {
        return null;
    }
}